from typing import List, Literal

from utils.JSON的输入和输出 import 写入json

"""
使用indx对desc进行分割 变成JSON
切换英 日 的方法 ctrl+F

输出是 处理后 / CARD_*.json
"""

file_names = ["CARD_Name", "CARD_Desc"]


# Name Desc 的 start 分别是 0 4
def progressiveProcess(
    file_name: str,
    indx_name: str,
    start: int,
    lang: Literal["en", "jp"],
    should_skip: bool = True,
) -> List[str]:

    # 读取二进制indx
    with open(f"output/2_res/{lang}/{indx_name}.txt", "rb") as f:
        hex_str_list = ("{:02X}".format(int(c)) for c in f.read())  # 定义变量接受文件内容
    dec_list = [int(s, 16) for s in hex_str_list]  # 将十六进制转换为十进制

    # 拿到desc的indx
    indx = []
    for i in range(start, len(dec_list), 8 if should_skip else 4):
        tmp = []
        for j in range(4):
            tmp.append(dec_list[i + j])
        indx.append(tmp)

    def fourToOne(x: List[int]) -> int:
        res = 0
        for i in range(3, -1, -1):
            res *= 16 * 16
            res += x[i]
        return res

    indx = [fourToOne(i) for i in indx]
    indx = indx[1:]
    """
    将解密后的CARD文件转换为JSON文件
    """

    def solve(data: bytes, desc_indx: List[int]) -> List[str]:
        res: List[str] = []
        for i in range(len(desc_indx) - 1):
            s = data[desc_indx[i] : desc_indx[i + 1]]
            s = s.decode("UTF-8")
            while len(s) > 0 and s[-1] == "\u0000":
                s = s[:-1]
            res.append(s)
        return res

    # 读desc文件进来
    with open(f"output/2_res/{lang}/{file_name}.txt", "rb") as f:
        data = f.read()

    return solve(data, indx)


if __name__ == "__main__":
    CARD_Name_en = progressiveProcess("CARD_Name", "CARD_Indx", 0, "en")
    CARD_Name_jp = progressiveProcess("CARD_Name", "CARD_Indx", 0, "jp")
    CARD_Desc_jp = progressiveProcess("CARD_Desc", "CARD_Indx", 4, "jp")
    combination = [
        {
            "indx": key,
            "name": {"jp": CARD_Name_jp[key], "en": CARD_Name_en[key]},
            "desc": CARD_Desc_jp[key],
        }
        for key, _ in enumerate(CARD_Name_en)
    ]
    写入json(combination, f"output/3_res/Name&Desc.json")
